import React, { useState } from 'react';
import styles from './index.less';
import { Form, DatePicker, Select, Button, Empty, Tooltip, Popconfirm } from 'antd';
import { useDebounceFn, useSetState } from 'ahooks';
import * as echarts from 'echarts';
import _ from 'lodash';
import moment from 'moment';
import { connect } from 'umi';

import { TRDefault, TRMessage } from '#/components/index.js';
import {
  CaretLeftOutlined,
  CaretRightOutlined,
  UploadOutlined,
  QuestionCircleOutlined,
} from '#/utils/antdIcons.js';
import { HttpCode } from '#/utils/contacts.js';

import { SERVER_URL_OBJ } from '@/../config/urlConfig';
import { Pointer, PageLoading, DimensionalSort } from '@/components/index.js';
import { TjStation } from '@/pages/ETrade/components/index.js';
import { export_json_to_excel } from '@/utils/fileExport.js';
import { useRem } from '@/hooks/index.js';

import BaseTable from './components/BaseTable';
import TraderCheckboxModal from './components/TraderCheckboxModal/index.jsx';
import { ChartDealTariff, ChartDealIncome, ChartDealPrice } from './components/Charts/index.js';
import {
  queryReanalyzeDataData,
  queryTradersOptions,
  getDynamicColumns,
  getDictionaryStatus,
  queryMarketList,
} from './services.js';
import { SELECT_DATA, OPTION_KEY, tableHead, operators, headerMap, detailList } from './helper';
import { formatJson, pointConvert, saveFloat } from './utils.js';
import { getTreeByCodes } from '@/utils';

const { RangePicker } = DatePicker;
const monthFormat = 'YYYYMMDD';
let dataInit: moment.Moment[] = [];
// 当前日期大于当前月的2号
if (moment().diff(moment().startOf('month'), 'days') > 1) {
  dataInit = [moment().startOf('month'), moment()];
} else {
  dataInit = [
    moment().subtract(1, 'months').startOf('month'),
    moment().subtract(1, 'months').endOf('month'),
  ];
}

const MyTraderSelect = (props: any) => {
  const {
    value = [],
    onChange,
    options = [],
    treeData = [],
    optionAll = [],
    className,
    buttonPermissions,
  } = props;
  const title = '交易员';
  const isEmpty = !treeData.length;
  React.useEffect(() => {
    if (!value.length) {
      onChange(optionAll);
    }
  }, [optionAll]);
  const onHandleModal = async () => {
    const hasSave =
      buttonPermissions.filter((item: any) => item.menuCode === 'CreateUserSelect').length > 0;
    if (!hasSave) {
      return TRMessage.info('请联系管理员获取相关权限');
    }
    if (isEmpty) return;
    const result = await TraderCheckboxModal.show({
      title,
      value,
      treeData,
    });
    if (result?.index === 1 && result.checkedKeys.length) {
      onChange(result.checkedKeys);
    }
    TraderCheckboxModal.dismiss();
  };
  const onDeselect = () => {
    if (value.length === 1) {
      onChange(optionAll);
    }
  };
  return (
    <div className={className}>
      <Select
        value={
          !value.length
            ? '请选择交易单元'
            : value.length === optionAll.length
            ? '全部'
            : `${value.length}项/${optionAll.length}项`
        }
        style={{
          minWidth: 120,
          // display: optionAll.length === value?.length || !value?.length ? 'none' : 'block',
          width: 200,
        }}
        options={options}
        // mode="multiple"
        // maxTagCount={1}
        // maxTagTextLength={value?.length > 1 ? 2 : 4}
        open={false}
        showSearch={false}
        showArrow={true}
        // fieldNames={{ label: '_stationName', value: '_stationCode', options: 'options' }}
        onClick={onHandleModal}
        onChange={onChange}
        onDeselect={onDeselect}
      />
      {/* <Select
        style={{
          minWidth: 120,
          display: optionAll.length !== value?.length && value?.length ? 'none' : 'block',
        }}
        placeholder="全部交易员"
        onClick={onHandleModal}
        open={false}
        onChange={onChange}
      /> */}
    </div>
  );
};
const PowerForecastAdjusted = ({ menuCode, buttonPermissions }: any) => {
  const [loading, setLoading] = useState(true),
    [error, setError] = useState(''),
    [listLoading, setListLoading] = useState(false),
    [columns, setColumns] = useState([]),
    [tableData, setTableData] = useState({}),
    [tableDataSource, setTableDataSource] = useState([]), //主表格数据
    [tableHeader, setTableHeader]: any = useState(), //表头
    [stations, setStations] = useState<any>([]), // 全部场站（平铺）
    [stationTree, setStationTree] = useState<any>([]), // 已选省份的场站树
    [optionAll, setOptionAll] = useState<any>([]), //所选省份全部场站(全选)
    [traderOptions, setTraderOptions] = useState<any>([]), //全部交易员
    [traderTree, setTraderTree] = useState<any>([]), //全部交易员(树)
    [traderOptionAll, setTraderOptionAll] = useState<any>([]), //交易员(全选)
    [param, setParam] = useState(SELECT_DATA), //灵活聚合项
    [form] = Form.useForm(),
    reSize = useRem(1920),
    [userList, setUserList] = useState<any>([]),
    [echartsTariffData, setEchartsTariffData] = useState<any>({}), //偏差电费组成
    [echartsIncomeData, setEchartsIncomeData] = useState<any>({}), //综合扣费收入
    [echartsPriceData, setEchartsPriceData] = useState<any>({}), //综合扣费电价
    [echartsParam, setEchartsParam]: any = useState(), //图表筛选参数
    [filterUnitOptions, setFilterUnitOptions] = useState(), //父维度筛选 交易单元列表
    [dateTime, setDateTime] = useState<any>(), //父维度筛选 时间
    [regions, setRegions] = useState<any[]>([]), // 全部省份
    [isFullScreenEcharts, setIsFullScreenEcharts] = useState(false), // 是否为图表全屏展示
    [isFullScreenTable, setIsFullScreenTable] = useState(false), // 是否为表格全屏展示
    [indicatorSummary, setIndicatorSummary] = useState<any>([]),
    [visible, setVisible] = useState(false), // 控制大数据查询前提示
    [issueStatusOption, setIssueStatusOption] = useState<any>([]),
    [exportParam, setExportParam] = useSetState({
      dateRange: [],
    }),
    [state, setState] = useSetState<any>({
      refData: [],
    }),
    [regionCode, setRegionCode] = useState<any>(''),
    [provinceId, setProvinceId] = useState('');

  React.useEffect(() => {
    init();
  }, []);

  /** handle data */
  async function init() {
    // 获取数据权限
    setLoading(true);
    const [res1, res2, res3] = await Promise.all([
      queryTradersOptions(),
      getDictionaryStatus(),
      queryMarketList(menuCode),
    ]);
    if (
      res1?.statusCode === HttpCode.SUCCESS &&
      res2?.statusCode === HttpCode.SUCCESS &&
      res3?.statusCode === HttpCode.SUCCESS
    ) {
      const _data = res1.data?.userList || [];
      setTraderOptions(
        _data.map((t: any) => ({
          label: t.name,
          value: t.userId + '',
        })),
      );
      setTraderTree(
        _data.map((t: any) => ({
          key: t.userId + '',
          title: t.name,
          phone: t.mobile,
          email: t.email,
        })),
      );
      let allStatus: any = [];
      const _issueStatusList: any = Object.entries(res2?.data).map((t) => {
        allStatus = allStatus.concat(t[1]);
        return {
          label: t[0],
          value: String(t[1]), //字符串下拉框才能正确选中
        };
      });
      allStatus = String(allStatus);
      _issueStatusList.unshift({ label: '全部', value: allStatus });
      setTraderOptionAll(_data.map((t: any) => t.userId + ''));
      setIssueStatusOption(_issueStatusList);
      const power = getTreeByCodes(['market', 'group', 'station'], res3.json).treeOptions;
      initDataPower(_data, allStatus, power);
    } else {
      setError('系统异常');
    }
    setLoading(false);
  }

  //获取省份对应交易单元
  const getStationOptions = (data: any) => {
    const _optionAll: any = _.flatten(
      data?.map((i: any) => i?.children?.map((y: any) => y.stationId)),
    );
    setOptionAll(_optionAll);
    setStationTree(data);
    form.setFieldsValue({
      unit: _optionAll,
    });
    return _optionAll;
  };

  const _onFinish = useDebounceFn(
    (values: any) => {
      setExportParam({
        dateRange: values.date,
      });
      // 查询
      const _formData: any = values,
        _date = _formData.date,
        _startDate = _date && moment(_date[0]).format('YYYY-MM-DD'),
        _endDate = _date && moment(_date[1]).format('YYYY-MM-DD'),
        _pointNum = _formData.point,
        _issueStatus = JSON.parse('[' + _formData.issueStatus + ']'),
        _tag = _formData.tag,
        _unit = _formData.unit,
        _trader = _formData.trader,
        _param = [SELECT_DATA[0], SELECT_DATA[1]];
      setParam(_param); //初始化聚合维度
      _fetchFile({
        cacheable: true,
        needTotal: true,
        operators: operators,
        order: _param,
        param: JSON.stringify({
          menuCode,
          regionCode: provinceId,
          stationIdList: _unit,
          dataTimeOrderType: _pointNum === '24' ? 'TWENTY_FOUR' : 'NINETY_SIX',
          startDate: _startDate,
          endDate: _endDate,
          issueStatus: _issueStatus,
          reanalyzeDataType: _tag === '1' ? 'CS' : 'JS',
          traderId: _trader,
        }),
        url: `${
          SERVER_URL_OBJ[`${CLIENT_ENV === 'dev' ? 'test' : CLIENT_ENV}` || 'release']
        }/reanalyze/forecastDataAdjustReanalyze/reanalyzeData`,
      });
    },
    { wait: 500 },
  );
  //默认请求
  const defaultRequest = (_stations: any, _regions: any, _userList: any, allStatus: any) => {
    // const stationsIds = _regions[0]?.children?.map((item: any) => item?.stationId || '');
    form.setFieldsValue({ region: _regions[0].value, unit: [] });
    const stationsIds = getStationOptions(_regions[0]?.children);

    const values = {
      date: dataInit,
      point: '96',
      issueStatus: allStatus,
      tag: '1',
      unit: stationsIds,
      trader: _userList,
    };
    setEchartsParam({
      ...values,
      timeOrder: '96',
    });
    //重新渲染表格数据
    _onFinish.run(values);
  };
  function initDataPower(_userList = [] as any, allStatus = [] as any, data = [] as any) {
    // 处理数据权限
    if (!data) {
      // setErrorMsg('暂无数据权限');
      return;
    }
    const _userList_ = _userList.map((t: any) => t.userId);
    setUserList(_userList_);
    const _stations = [] as any;
    const _rs = [] as any;
    data.map((x: any) => {
      // 省份
      _rs.push(x);
      (x?.children || []).map((y: any) => {
        // 公司
        (y?.children || []).map((z: any) => {
          // 场站
          _stations.push(z);
        });
      });
    });
    setRegionCode(_rs?.[0]?.marketId || '');
    setProvinceId(_rs?.[0]?.provinceId || '');
    setRegions(_rs);
    setStations(_stations);
    defaultRequest(_stations, _rs, _userList_, allStatus);
  }
  //切换省份
  const onRegionChange = (value: any, selectOptions: any) => {
    setRegionCode(selectOptions.marketId);
    setProvinceId(selectOptions.provinceId);
    form.setFieldsValue({
      unit: [],
    });
    getStationOptions(selectOptions.children);
  };
  //取出非合计行默认第一行 最后一个子维度 作为echarts的横坐标
  const _getXAXIS = (data: any, arr: any[]) => {
    const _temp: any[] = [];
    const recursion = (item: any, index: number): any[] => {
      _temp.push({
        tag: item[0]?.tag,
        title: item[0]?.title,
      });
      if (item[0]?.children instanceof Array && item.length > 0) {
        return recursion(item[0].children, index - 1);
      }
      return _temp;
    };
    return recursion(data, arr.length - 1);
  };

  const getClassName = () => {
    let classNameEcharts = styles.charts;
    let classNameTable = styles.table;
    if (isFullScreenEcharts) {
      classNameEcharts = `${styles.chartsFullWidth}`;
      classNameTable = `${styles.tableNoWidth}`;
    } else if (isFullScreenTable) {
      classNameEcharts = `${styles.chartsNoWidth}`;
      classNameTable = `${styles.tableFullWidth}`;
    }

    return {
      classNameEcharts,
      classNameTable,
    };
  };

  const confirm = useDebounceFn(
    () => {
      setVisible(false);
      form && form.submit();
    },
    { wait: 500 },
  );

  const handleVisibleChange = (newVisible?: boolean) => {
    const { date, unit } = form.getFieldsValue();
    if (date && unit.length > 0) {
      const days = date[1].diff(date[0], 'days') + 1;
      if (days * unit.length > 900) {
        setVisible(!!newVisible);
      } else {
        confirm.run();
      }
    } else if (!date || !unit.length) {
      setVisible(false);
    } else {
      confirm.run();
    }
  };
  /**建立echarts链接 */
  const getRef: any = (refData: any) => {
    const arr = [...state.refData];
    state.refData.push(refData);
    arr.push(refData);
    if (arr.length >= 2) {
      echarts.connect([...arr]);
    }
    setState({
      refData: arr,
    });
  };
  //根据父维度 筛选出图表所需数据  return:最后一个维度数组
  const _getFilterXAXIS = (data: any, arr: any[]): any[] => {
    const _echartsParam = _.cloneDeep(echartsParam);
    //取最后一个维度 第一行数据
    const recursion = (item: any, index: number): any[] => {
      const _item: any[] = [];
      item.forEach((t: any) => {
        if (t.title === '合计') return;
        _item.push(t);
      });
      let _temp: any[] = [];
      //如果已经是最后一个维度
      if (arr.length - 1 <= index) {
        return _item;
      }
      _item.forEach((t: any) => {
        t.title === _echartsParam[OPTION_KEY[arr[index]]] &&
          (_temp = recursion(t.children, index + 1));
      });
      return _temp;
    };
    return recursion(data, 0);
  };
  //获取默认第一行 根据传入维度递归获取数据
  const _getDimensionData = (data: any, deepIndex: number): any[] => {
    if (deepIndex) {
      return _getDimensionData(
        data[0].children.length ? data[0].children : data[1].children,
        deepIndex - 1,
      );
    }
    return data;
  };
  //dealFunc
  const dealFunc = (tag: string, meta: string[], title: any, value: any[]) => {
    let obj: any = {};
    obj = {
      title:
        tag === '时点'
          ? pointConvert(title, form)
          : tag === '日期'
          ? title.replaceAll('-', '')
          : title,
      tag: tag,
    };

    meta.forEach((_t: string, _i: number) => {
      if (_i > 1) {
        obj[headerMap[_t]] = _t.includes('电量')
          ? parseFloat(value[_i]).toFixed(3)
          : parseFloat(value[_i]).toFixed(2);
      } else {
        obj[headerMap[_t]] = value[_i];
      }
    });
    //交易单元不展示交易员
    obj[headerMap['交易员']].includes(',') && (obj[headerMap['交易员']] = '-');

    const _issueStatus = obj[headerMap['下发状态']];
    const _issueStatusOption = issueStatusOption.slice(1);
    obj[headerMap['下发状态']] = _issueStatus.includes(',')
      ? '-'
      : _issueStatusOption.find((t: any) => t.value.includes(_issueStatus)).label;
    return obj;
  };
  //dealFunc
  const totalDealFunc = (tag: string, meta: string[], title: any, value: any[]) => {
    let obj: any = {};
    obj = {
      title: title,
      tag: tag,
    };
    meta.forEach((_t: string, _i: number) => {
      if (_i > 1) {
        obj[headerMap[_t]] = _t.includes('电量')
          ? parseFloat(value[_i]).toFixed(3)
          : parseFloat(value[_i]).toFixed(2);
      } else {
        obj[headerMap[_t]] = value[_i];
      }
    });
    obj.children = [];

    obj[headerMap['交易员']] = obj[headerMap['交易员']].includes(',')
      ? '-'
      : obj[headerMap['交易员']];

    const _issueStatus = obj[headerMap['下发状态']];
    const _issueStatusOption = issueStatusOption.slice(1);
    obj[headerMap['下发状态']] = _issueStatus.includes(',')
      ? '-'
      : _issueStatusOption.find((t: any) => t.value.includes(_issueStatus)).label;
    return obj;
  };
  //处理表格数据 dataSource表格数据 postdata选项
  const getNewDataSource = (dataSource: any, order: any, selectedKeys: string[] = []) => {
    if (!dataSource) return [];
    const _total = dataSource.data.total,
      indicatorSummaryEnum = [
        {
          title: '综合结算',
          beforeList: ['before_comprehensiveDeductionIncome'],
          afterList: ['after_comprehensiveDeductionIncome'],
          childrenObj: {
            after_comprehensiveDeductionIncome: 13,
            before_comprehensiveDeductionIncome: 11,
          },
        },
        {
          title: '中长期收入',
          beforeList: ['mediumAndLongTerm_before_mediumAndLongTermIncome'],
          afterList: ['mediumAndLongTerm_after_mediumAndLongTermIncome'],
          childrenObj: {
            mediumAndLongTerm_after_mediumAndLongTermIncome: 20,
            mediumAndLongTerm_before_mediumAndLongTermIncome: 18,
          },
        },
        {
          title: '现货收入',
          afterList: [
            'realTime_after_realTimeSettlementIncome',
            'dayAhead_after_settlementIncomeBeforeTheDay',
          ],
          beforeList: [
            'dayAhead_before_settlementIncomeBeforeTheDay',
            'realTime_before_realTimeSettlementIncome',
          ],
          childrenObj: {
            dayAhead_before_settlementIncomeBeforeTheDay: 23,
            realTime_before_realTimeSettlementIncome: 29,
            realTime_after_realTimeSettlementIncome: 31,
            dayAhead_after_settlementIncomeBeforeTheDay: 26,
          },
        },
        {
          title: '回收费用',
          afterList: [
            'deviationRecovery_after_excessProfitRecovery',
            'deviationRecovery_after_mediumAndLongTermExcessRecovery',
          ],
          beforeList: [
            'deviationRecovery_before_excessProfitRecovery',
            'deviationRecovery_before_mediumAndLongTermExcessRecovery',
          ],
          childrenObj: {
            deviationRecovery_before_excessProfitRecovery: 32,
            deviationRecovery_before_mediumAndLongTermExcessRecovery: 33,
            deviationRecovery_after_excessProfitRecovery: 34,
            deviationRecovery_after_mediumAndLongTermExcessRecovery: 35,
          },
        },
        {
          title: '考核费用',
          afterList: [
            'appraisalExpense_after_forecastAccuracyAppraisal',
            'appraisalExpense_after_absoluteErrorAssessment',
          ],
          beforeList: [
            'appraisalExpense_before_forecastAccuracyAppraisal',
            'appraisalExpense_before_absoluteErrorAssessment',
          ],
          childrenObj: {
            appraisalExpense_before_forecastAccuracyAppraisal: 36,
            appraisalExpense_before_absoluteErrorAssessment: 37,
            appraisalExpense_after_forecastAccuracyAppraisal: 38,
            appraisalExpense_after_absoluteErrorAssessment: 39,
          },
        },
      ];
    const indicatorSummaryList = [];
    indicatorSummaryEnum?.forEach((ise) => {
      const indicatorSlide = {
        name: ise.title,
        count: 0,
      };
      const isContainList = [],
        isBeforeList = [],
        isAfterList = [];
      let beforeSum = 0,
        afterSum = 0;
      ise.beforeList?.forEach((c) => {
        if (selectedKeys.includes(c)) {
          isContainList.push(c);
          isBeforeList.push(c);
        }
      });
      ise.afterList?.forEach((c) => {
        if (selectedKeys.includes(c)) {
          isContainList.push(c);
          isAfterList.push(c);
        }
      });
      if (!isContainList?.length) return;
      if (isBeforeList?.length) {
        isBeforeList?.forEach((b) => {
          beforeSum += parseFloat(_total[ise.childrenObj[b]]);
        });
        indicatorSlide.before = (beforeSum / 10000).toFixed(4);
      }
      if (isAfterList?.length) {
        isAfterList?.forEach((b) => {
          afterSum += parseFloat(_total[ise.childrenObj[b]]);
        });
        indicatorSlide.after = (afterSum / 10000).toFixed(4);
      }
      indicatorSlide.count = saveFloat(afterSum, beforeSum);
      indicatorSummaryList.push(indicatorSlide);
    });
    setIndicatorSummary(indicatorSummaryList);
    const formatForTable = (item: any, optionName: any, index = 0) => {
      const arr: any[] = [];
      Object.entries(item).map((t: any) => {
        if (t[0] === 'total') {
          return;
        }
        //最后一个维度为数组
        if (t[1] instanceof Array) {
          arr.push(dealFunc(optionName[index], dataSource.meta, t[0], t[1]));
          return;
        }
        const obj = dealFunc(optionName[index], dataSource.meta, t[0], t[1].total);
        obj.children = formatForTable(t[1], optionName, index + 1);
        arr.push(obj);
      });
      arr.sort((a: any, b: any) => {
        if (optionName[index] === '交易单元') {
          return a.title.localeCompare(b.title, 'zh-CN');
        }
        //默认时点排序方式
        return a.title > b.title ? 1 : -1;
      });
      return arr;
    };
    // 添加合计行
    const result = [
      totalDealFunc(order[0], dataSource.meta, '合计', dataSource.data.total),
      ...formatForTable(dataSource.data, order),
    ];
    return result;
  };
  const flattenDeep = (list: any = [], selectedKeys: string[] = []) => {
    list?.forEach((l: any) => {
      // 默认选中
      if (l?.checkbox === 1 && l?.key) {
        selectedKeys.push(l.key);
      }
      l?.children?.length && flattenDeep(l.children, selectedKeys);
    });
    return selectedKeys;
  };
  const filterColumns = (list: string[] = []) => {
    const headerList: any = [];
    tableHead?.forEach((t) => {
      if (list?.includes(t?.field) || ['trader', 'issueStatus'].includes(t?.field)) {
        headerList.push(t);
      }
    });
    if (Object.keys(tableData)?.length) {
      getNewDataSource(tableData, param, list);
    }
    setTableHeader(headerList);
  };
  //请求表格数据
  async function _fetchFile(postdata: any) {
    const { param, order } = postdata;
    const regionCode = JSON.parse(param)?.regionCode;

    setParam(order);
    setListLoading(true);
    setTableDataSource([]);

    const res = await queryReanalyzeDataData(postdata).catch(() => {});
    const columnsRes = await getDynamicColumns({
      regionCode,
      menuCode,
    });

    setListLoading(false);

    if (res.statusCode === HttpCode.SUCCESS) {
      let selectedKeys = [];
      selectedKeys = flattenDeep(columnsRes?.data || [], selectedKeys);
      filterColumns(selectedKeys);
      setTableData(res?.data || {});
      const data: any = getNewDataSource(res?.data, order, selectedKeys);
      setTableDataSource(data);
      setColumns(columnsRes?.data || []);

      if (data.length) {
        const _data = _.cloneDeep(data);
        //设置图表数据
        const _echarsData = _getXAXIS(_data.splice(1), SELECT_DATA);
        //设置父维度列表值
        setFilterUnitOptions(
          (form.getFieldValue('unit')?.length ? form.getFieldValue('unit') : optionAll).map(
            (t: any) => {
              const item = stations.find((_t: any) => t == _t.stationId);
              return {
                label: item.stationName,
                value: item.stationName,
              };
            },
          ),
        );
        setDateTime(form.getFieldValue('date'));
        //设置父维度选择默认值【合约量价图】默认：第一个维度
        setEchartsParam({
          date:
            order.includes('日期') &&
            moment(_echarsData.find((t) => t.tag === '日期').title).format('YYYYMMDD'),
          unit:
            order.includes('交易单元') && _echarsData.find((t) => t.tag === '交易单元').title + '',
          timeOrder:
            order.includes('时点') && form.getFieldValue('point') === '24' ? '0100' : '0015',
        });
      }
    }
  }
  const onexport = () => {
    if (!tableDataSource.length) return;
    const hasSave =
      buttonPermissions.filter(
        (item: any) => item.menuCode === 'ForecastDataAdjustReanalyzeExportButton',
      ).length > 0;
    if (!hasSave) {
      return TRMessage.info('请联系管理员获取相关权限');
    }
    const _date = exportParam.dateRange;
    const filename = `预测功率调整复盘-${moment(_date[0]).format('YYYYMMDD')}_${moment(
      _date[1],
    ).format('YYYYMMDD')}`;
    const params: any = {
      multiHeader: [],
      header: [''],
      data: [],
      merges: [
        'B1:C1',
        'D1:I1',
        'J1:L1',
        'M1:Q1',
        'R1:W1',
        'X1:AC1',
        'AD1:AH1',
        'A3:A2',
        'B3:B2',
        'C3:C2',
        'D3:D2',
        'E3:E2',
        'F3:F2',
        'G3:G2',
        'H3:H2',
        'I3:I2',
        'J3:J2',
        'K3:K2',
        'L3:L2',
        'M3:M2',
        'N2:O2',
        'P2:Q2',
        'R3:R2',
        'S3:S2',
        'T2:U2',
        'V2:W2',
        'X2:Z2',
        'AA2:AC2',
        'AD2:AD3',
        'AE2:AF2',
        'AG2:AH2',
        'AI2:AJ2',
        'AK2:AL2',
        'AM2:AN2',
        'AO2:AP2',
      ],
      filename,
    };
    const data = tableDataSource;
    const dataFalt: any[] = [];
    data.map((x: any) => {
      dataFalt.push(x);
      (x?.children || []).map((y: any) => {
        dataFalt.push(y);
        (y?.children || []).map((z: any) => {
          dataFalt.push(z);
          (z?.children || []).map((e: any) => {
            dataFalt.push(e);
          });
        });
      });
    });
    const filterVal: string[] = ['title'];
    const multiHeader2 = [param[0]],
      multiHeader = ['聚合维度'];
    tableHeader?.forEach((item: any) => {
      //第一级
      multiHeader.push(params.multiHeader.includes(item.parentName) ? '' : item.parentName);
      //第二级
      multiHeader2.push(
        item.secondParentName
          ? item.secondParentName === multiHeader2[multiHeader2.length - 1]
            ? ''
            : item.secondParentName || ''
          : item.name,
      );
      //最后一级
      params.header.push(item.name);
      filterVal.push(item.field);
    });
    params.multiHeader = [multiHeader, multiHeader2];
    params.data = formatJson(filterVal, dataFalt);
    export_json_to_excel(params);
  };
  //根据筛选参数 重绘图表
  const repaint = () => {
    const _echarsData = _getFilterXAXIS(tableDataSource, param);
    const _xaxis = _echarsData.map((t) => t.title);
    setEchartsTariffData({
      XAXIS: _xaxis,
      DeviationOfComprehensiveDeductionIncome: _echarsData.map(
        (t) => t.deviationOfComprehensiveDeductionIncome,
      ),
      MediumAndLongTermTncomeDeviation: _echarsData.map((t) => t.mediumAndLongTermCostDeviation),
      SpotRevenueDeviation: _echarsData.map((t) => t.spotRevenueDeviation),
      RecoveryCostDeviation: _echarsData.map((t) => t.recoveryCostDeviation),
      AssessmentCostDeviation: _echarsData.map((t) => t.assessmentCostDeviation),
    });
    setEchartsIncomeData({
      XAXIS: _xaxis,
      BeforeComprehensiveDeductionIncome: _echarsData.map(
        (t) => t.before_comprehensiveDeductionIncome,
      ),
      AfterComprehensiveDeductionIncome: _echarsData.map(
        (t) => t.after_comprehensiveDeductionIncome,
      ),
      DeviationOfComprehensiveDeductionIncome: _echarsData.map(
        (t) => t.deviationOfComprehensiveDeductionIncome,
      ),
    });
    setEchartsPriceData({
      XAXIS: _xaxis,
      BeforeComprehensiveDeductionTariff: _echarsData.map(
        (t) => t.before_comprehensiveDeductionTariff,
      ),
      AfterComprehensiveDeductionTariff: _echarsData.map(
        (t) => t.after_comprehensiveDeductionTariff,
      ),
      DeviationOfComprehensiveDeductionPrice: _echarsData.map(
        (t) => t.deviationOfComprehensiveDeductionPrice,
      ),
    });
  };

  React.useEffect(() => {
    if (tableDataSource.length > 0) {
      repaint();
    }
  }, [echartsParam]);
  const _onReset = useDebounceFn(
    () => {
      form.resetFields();
      const regionId = form.getFieldValue('region') ?? '';
      onRegionChange(
        regionId,
        regions?.find((i) => i.marketId === regionId),
      );
      setTableDataSource([]);
      defaultRequest(stations, regions, userList, issueStatusOption?.[0]?.value);
    },
    { wait: 500 },
  );
  const _renderHeader = () => {
    const initialValues = () => {
      return {
        region: regions[0].value,
        date: dataInit,
        issueStatus: issueStatusOption?.[0]?.value,
        point: '96',
        tag: '1',
      };
    };
    return (
      <div className={styles.header}>
        <Form
          form={form}
          initialValues={initialValues()}
          className={styles.formStyles}
          onFinish={_onFinish.run}
        >
          <Form.Item name="region" className={styles.cell_item}>
            <Select
              options={regions}
              style={{ width: 200 }}
              placeholder="请选择交易中心"
              showSearch={true}
              onChange={(e, e2) => {
                onRegionChange(e, e2);
              }}
            />
          </Form.Item>
          <Form.Item name="unit" className={styles.cell_item}>
            <TjStation options={stationTree} />
          </Form.Item>
          <Form.Item
            name="date"
            className={styles.cell_item}
            rules={[{ required: true, message: '请选择日期' }]}
          >
            <RangePicker className={styles.select_date} format={'YYYYMMDD'} separator={'-'} />
          </Form.Item>
          <Form.Item name="trader" className={styles.cell_item}>
            <MyTraderSelect
              treeData={traderTree}
              options={traderOptions}
              optionAll={traderOptionAll}
              buttonPermissions={buttonPermissions}
            />
          </Form.Item>
          <Form.Item name="issueStatus" className={styles.cell_item}>
            <Select
              options={issueStatusOption}
              style={{ width: 120 }}
              placeholder="全部下发状态"
              showSearch={true}
            />
          </Form.Item>
          <Form.Item name="point" className={styles.cell_item}>
            <div className={styles.tag}>
              {/* <Radio.Group defaultValue="96" buttonStyle="solid" size="small">
                <Radio.Button value="24">24</Radio.Button>
                <Radio.Button value="96">96</Radio.Button>
              </Radio.Group> */}
              <Pointer
                options={[
                  { label: '24', value: '24' },
                  { label: '96', value: '96' },
                ]}
                data={'96'}
              />
            </div>
          </Form.Item>
          <Form.Item name="tag" className={styles.cell_item}>
            <div className={styles.tag}>
              <Pointer
                options={[
                  { label: '测算数据', value: '1' },
                  { label: '结算数据', value: '2' },
                ]}
                data={'1'}
              />
              {/* <Radio.Group defaultValue="1" buttonStyle="solid">
                <Radio.Button value="1">测算数据</Radio.Button>
                <Radio.Button value="2">结算数据</Radio.Button>
              </Radio.Group> */}
            </div>
          </Form.Item>
          <Popconfirm
            title="您选择的数据量较大，可能延长加载时间或引起页面崩溃，是否确认查询？"
            visible={visible}
            onVisibleChange={handleVisibleChange}
            onConfirm={() => confirm.run()}
            onCancel={() => setVisible(false)}
            okText="确认"
            cancelText="取消"
          >
            <Button className={styles.submit} type="primary" htmlType="submit">
              查询
            </Button>
          </Popconfirm>
          <Button className={styles.reset} htmlType="reset" onClick={_onReset.run} ghost>
            重置
          </Button>
          <div
            className={`${styles.import} ${!tableDataSource.length && styles.disabled}`}
            onClick={onexport}
          >
            <UploadOutlined style={{ fontSize: '0.12rem' }} />
            导出
          </div>
        </Form>
      </div>
    );
  };
  //展板
  const _renderBoard = () => {
    if (!tableDataSource.length) return;
    return (
      <div className={styles.board}>
        {indicatorSummary.map((t: any, i: number) => {
          return (
            <div className={styles.item} key={i}>
              <div className={styles.right}>
                <p className={styles.title}>
                  {t.name}
                  <Tooltip title={detailList[i]}>
                    <QuestionCircleOutlined style={{ color: '#FD4F43', marginLeft: '0.04rem' }} />
                  </Tooltip>
                </p>
                <span className={styles.price}>
                  {t.count < 0 ? '' : '+'}
                  {t.count}
                </span>
                <span className={styles.unit}>万元</span>
              </div>
              <div className={styles.left}>
                {t.before ? (
                  <React.Fragment>
                    <p className={styles.label}>调节前</p>
                    <p className={styles.price}>{t.before}</p>
                  </React.Fragment>
                ) : null}
                {t.after ? (
                  <React.Fragment>
                    <p className={styles.label} style={{ color: '#30D180' }}>
                      调节后
                    </p>
                    <p className={styles.price} style={{ color: '#30D180' }}>
                      {t.after}
                    </p>
                  </React.Fragment>
                ) : null}
              </div>
            </div>
          );
        })}
      </div>
    );
  };
  //表格图表内容区域渲染
  const _renderContent = () => {
    if (listLoading)
      return (
        <div className={styles.emty}>
          <PageLoading />
        </div>
      );
    // if (dataLock) return <div className={styles.emty}><Empty image={img_lock} imageStyle={{ height: '150px' }} description="您没有相关权限，请联系管理员" /></div>;
    if (!tableDataSource.length) return <TRDefault type={'empty'} />;
    /*获取设置选择器下拉列表项*/
    const pointOptions =
      param.includes('时点') && param.indexOf('时点') < param.length - 1
        ? _getDimensionData(tableDataSource, param.indexOf('时点')).map((t) => ({
            label: t.title,
            value: t.title,
          }))
        : [];
    //重新聚合
    const _polymerize = (options: any) => {
      setParam(options);
      //重新渲染表格数据
      const _formData: any = form.getFieldsValue(true),
        _date = _formData.date,
        _startDate = _date && moment(_date[0]).format('YYYY-MM-DD'),
        _endDate = _date && moment(_date[1]).format('YYYY-MM-DD'),
        _pointNum = _formData.point,
        _issueStatus = JSON.parse('[' + _formData.issueStatus + ']'),
        _tag = _formData.tag,
        _unit = _formData.unit,
        _trader = _formData.trader;
      _fetchFile({
        cacheable: true,
        needTotal: true,
        operators: operators,
        order: options,
        param: JSON.stringify({
          menuCode,
          regionCode: provinceId,
          stationIdList: _unit,
          dataTimeOrderType: _pointNum === '24' ? 'TWENTY_FOUR' : 'NINETY_SIX',
          startDate: _startDate,
          endDate: _endDate,
          issueStatus: _issueStatus,
          reanalyzeDataType: _tag === '1' ? 'CS' : 'JS',
          traderId: _trader,
        }),
        url: `${
          SERVER_URL_OBJ[`${CLIENT_ENV === 'dev' ? 'test' : CLIENT_ENV}` || 'release']
        }/reanalyze/forecastDataAdjustReanalyze/reanalyzeData`,
      });
    };
    const _selectUnitOnChange = (value: any) => {
      setEchartsParam({
        ...echartsParam,
        unit: value,
      });
    };
    const _selectDateOnChange = (value: any) => {
      setEchartsParam({
        ...echartsParam,
        date: value.format('YYYYMMDD'),
      });
    };
    const _selectPointOnChange = (value: any) => {
      setEchartsParam({
        ...echartsParam,
        timeOrder: value,
      });
    };
    //控制日历可选范围
    const disabledDate = (current: any) => {
      const _date = dateTime;
      return (current && current < _date[0].startOf('day')) || current > _date[1].endOf('day');
    };
    return (
      <>
        <div className={[styles.leftBox, getClassName().classNameTable].join(' ')}>
          <div
            className={styles.leftArrow}
            onClick={() => {
              setIsFullScreenTable(!isFullScreenTable);
            }}
          >
            {isFullScreenTable ? <CaretLeftOutlined /> : <CaretRightOutlined />}
          </div>
          <DimensionalSort
            reSize={reSize}
            optionsArray={SELECT_DATA}
            option={param}
            onClick={_polymerize}
            columns={columns}
            menuCode={menuCode}
            regionCode={regionCode}
            filterColumns={filterColumns}
          />
          <BaseTable
            tableData={tableDataSource}
            tableHeader={tableHeader}
            text={param[0]}
            issueStatusKeys={issueStatusOption.map((t: any) => t.label)}
          />
        </div>
        <div className={[styles.rightBox, getClassName().classNameEcharts].join(' ')}>
          <div className={styles.filter_group}>
            <div className={styles.flex}>
              {param.map((t: any, i: number) => {
                if (t === '交易单元' && param[param.length - 1] !== '交易单元') {
                  {
                    return (
                      <Select
                        key={i}
                        className={styles.filter_unit}
                        style={{ marginLeft: i === 0 ? 0 : '.16rem' }}
                        showSearch
                        placeholder="选择交易单元"
                        onChange={_selectUnitOnChange}
                        value={echartsParam.unit}
                        options={filterUnitOptions}
                        filterOption={(input, option) => {
                          return (option?.label as unknown as string)
                            .toLowerCase()
                            .includes(input.toLowerCase());
                        }}
                      />
                    );
                  }
                }
                if (t === '日期' && param[param.length - 1] !== '日期') {
                  {
                    return (
                      <DatePicker
                        key={i}
                        onChange={_selectDateOnChange}
                        inputReadOnly
                        allowClear={false}
                        className={styles.filter_date}
                        style={{ marginLeft: i === 0 ? 0 : '.16rem' }}
                        value={moment(echartsParam.date)}
                        format={monthFormat}
                        disabledDate={disabledDate}
                      />
                    );
                  }
                }
                if (t === '时点' && param[param.length - 1] !== '时点') {
                  {
                    return (
                      <Select
                        key={i}
                        className={styles.filter_point}
                        style={{ marginLeft: i === 0 ? 0 : '.16rem' }}
                        placeholder="选择时点"
                        onChange={_selectPointOnChange}
                        value={echartsParam.timeOrder}
                        options={pointOptions}
                      />
                    );
                  }
                }
              })}
            </div>
          </div>
          <div className={styles.content_box}>
            <div
              className={styles.rightArrow}
              onClick={() => {
                setIsFullScreenEcharts(!isFullScreenEcharts);
              }}
            >
              {isFullScreenEcharts ? <CaretRightOutlined /> : <CaretLeftOutlined />}
            </div>
            {!echartsTariffData?.XAXIS?.length ? (
              <div className={styles.emty}>
                <TRDefault type="emptysm" />
              </div>
            ) : (
              <>
                <div className={styles.title} style={{ paddingTop: 0 }}>
                  偏差电费组成 <span className={styles.label}>单位：元</span>
                </div>
                <div style={{ flex: 1, minHeight: '200px' }}>
                  <ChartDealTariff
                    isFullScreenEcharts={isFullScreenEcharts}
                    data={echartsTariffData}
                    scale={reSize / 100}
                    getRef={getRef}
                  />
                </div>
                <div className={styles.title}>
                  综合扣费收入 <span className={styles.label}>单位：元</span>
                </div>
                <div style={{ flex: 1, minHeight: '200px' }}>
                  <ChartDealIncome
                    isFullScreenEcharts={isFullScreenEcharts}
                    data={echartsIncomeData}
                    scale={reSize / 100}
                    getRef={getRef}
                  />
                </div>
                <div className={styles.title}>
                  综合扣费电价 <span className={styles.label}>单位：元/MWh</span>
                </div>
                <div style={{ flex: 1, minHeight: '200px' }}>
                  <ChartDealPrice
                    isFullScreenEcharts={isFullScreenEcharts}
                    data={echartsPriceData}
                    scale={reSize / 100}
                    getRef={getRef}
                  />
                </div>
              </>
            )}
          </div>
        </div>
      </>
    );
  };
  if (loading) return <PageLoading />;
  if (error) return <TRDefault type="error" message={error} />;
  if (!stations?.length) return <TRDefault type="lock" />;
  return (
    <>
      {_renderHeader()}
      {_renderBoard()}
      <div className={styles.content_body}>
        <div className={styles.content}> {_renderContent()}</div>
      </div>
    </>
  );
};
export default connect(({ global }: any) => ({
  menuCode: global.configure.menuCode,
  buttonPermissions: global.configure.buttonPermissions,
}))(PowerForecastAdjusted);
